package interview.huawei.myself.online3;

import java.util.ArrayDeque;
import java.util.Iterator;
import java.util.LinkedList;

/**
 * @Author CandyWall
 * @Date 2022/3/19--14:34
 * @Description
 */
public class Main {
    public static void main(String[] args) {
        String records = "a(b(c)<3>d)<2>";
        ArrayDeque<Character> stack = new ArrayDeque<>();
        for (char ch : records.toCharArray()) {
            if (ch == '>') {
                String count_str = "";
                // 看下栈顶元素是不是'<'
                while (stack.peekLast() != '<') {
                    // 栈顶元素出栈
                    count_str = stack.removeLast() + count_str;
                }
                // 获取到重复次数
                int count = Integer.parseInt(count_str);
                // pop掉 '<' 符号
                stack.removeLast();

                // 取出要被重复的内容
                if (stack.peekLast() == ')') {
                    LinkedList<Character> tempList = new LinkedList<>();
                    // pop掉 ')' 符号
                    stack.removeLast();
                    while (stack.peekLast() != '(') {
                        tempList.addFirst(stack.removeLast());
                    }
                    // pop掉 '(' 符号
                    stack.removeLast();
                    // 将内容重复count次然后push进stack栈
                    for (int i = 0; i < count; i++) {
                        Iterator<Character> ite = tempList.iterator();
                        while (ite.hasNext()) {
                            stack.addLast(ite.next());
                        }
                    }
                }
            } else {
                stack.addLast(ch);
            }
        }
        StringBuilder sb = new StringBuilder();
        while (!stack.isEmpty()) {
            sb.append(stack.pop());
        }
        System.out.println(sb);
    }
}
